package main

import (
	store "eth-client-demo/contracts"
	"eth-client-demo/services"
	"fmt"
	"log"

	"github.com/ethereum/go-ethereum/common"
)

func main() {
	// 初始化客户端
	rpcURL := "https://ethereum-sepolia-rpc.publicnode.com"
	privateKey := ""
	client, err := services.NewEthClient(rpcURL, privateKey)
	if err != nil {
		log.Fatal("初始化客户端失败:", err)
	}
	fmt.Println("客户端地址:", client.Address.Hex())
	fmt.Println("频道:", client.ChainID)
	//使用区块高度查询区块
	blockNumber := big.NewInt(5671744)
	block, err := client.GetBlockByNumber(blockNumber)
	if err != nil {
		fmt.Println("查询错误:", err)
	}
	fmt.Println(block.Number().Uint64()) // 5671744
	//使用区块hash查询区块
	block, err = client.GetBlockByHash(block.Hash().Hex())
	if err != nil {
		fmt.Println("查询错误:", err)
	}
	fmt.Println(block.Hash().Hex())
	//查询余额
	balance, err := client.GetBalance(client.Address.Hex())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("交易前余额:", balance)
	//利用交易哈希查询交易详情
	tranHash := "0x438efcaef0576ea3924dea9d8ab1a97478a75d74253e4cac6ee4053a0498402e"
	result, isPending, err1 := client.GetTransaction(tranHash)
	if err1 != nil {
		fmt.Println("查询错误:", err)
	}
	if isPending {
		fmt.Println("交易成功:")
	} else {
		fmt.Println("交易正在进行")
	}
	//打印交易的所有内容
	if result != nil {
		fmt.Println("燃料费：", result.Gas())
		fmt.Println("燃料价格：", result.GasPrice())
		fmt.Println("随机字符串：", result.Nonce())
		fmt.Println("参数：", result.Data())
		fmt.Println("频道：", result.ChainId())
		fmt.Println("接收方地址：", result.To())
	}
	//查询交易收据
	_, err2 := client.GetReceipt(tranHash)
	if err2 != nil {
		fmt.Println("查询错误:", err2)
	}
	//fmt.Println(result1)
	//发起eth转账
	value := big.NewInt(1000000000000000) //0.01eth
	toAddress := "0x91D8CC6fe6438a9D591a57fFCfAe5CD2FE4E879A"
	err = client.TransferETH(value, toAddress)
	if err != nil {
		log.Fatal("交易失败:", err)
	}
	fmt.Println("交易成功")
	balance, err = client.GetBalance(toAddress)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("交易后余额:", balance)
	//部署合约
	err = client.DeployContract()
	if err != nil {
		log.Fatal("部署失败：", err)
	}
	fmt.Println("部署合约成功:")

	//执行合约
	contractAddress := "0x6C528a28779ba0686DfD964e8Ff18921471939f5"
	tx, err := client.ExecuteTheContract(contractAddress)
	if err != nil {
		return
	}
	fmt.Println("交易哈希:", tx.Hash().Hex())
	fmt.Println("交易 Nonce:", tx.Nonce())
	fmt.Println("交易 Gas:", tx.Gas())
	//查询合约数据
	contractAddr := common.HexToAddress(contractAddress)
	instance, _ := store.NewStore(contractAddr, client.Client)
	key := [32]byte{}
	copy(key[:], []byte("name"))
	value, _ = instance.Items(nil, key)
	fmt.Println("查询结果:", string(value[:]))
}
